//
//  FanObstacle.m
//  StarBugs
//
//  Created by ?? ? on 2/21/12.
//  Copyright 2012 antisword@playorca.com. All rights reserved.
//

#include "Object/FanObstacle.h"
#include "Util/ImageManager.h"
#include "Util/Util.h"
#include "Layer/GameUILayer.h"

int windPos[4][2] = 
{
    {15, 10}, {12, 4}, {13, -2}, {10, -7},
};

int countPlus[4] = 
{
    1, 3, 2, 1
};

FanObstacle::~FanObstacle()
{
    //    removeChild(mainSprite, true);
//    if(frameArray)
//    {
//        frameArray->removeAllObjects();
//        frameArray->release();
//        frameArray = NULL;
//    }
//    
//    if(mainSprite)
//    {
//        mainSprite->removeAllChildrenWithCleanup(true);
//        mainSprite->release();
//        mainSprite = NULL;
//    }
    
    for(int i =0; i < 4; i++)
    {
        windFrameArray[i]->removeAllObjects();
        windFrameArray[i]->release();
        windFrameArray[i] = NULL;
    }
}

FanObstacle::FanObstacle()
{
    mainSprite = new CCSprite();
    mainSprite->init();
    mainSprite->autorelease();
    addChild(mainSprite);
    
    fanSprite = ImageManager::getSpriteWithXml2(kImagesheet_GameSource, "windpen");
    mainSprite->addChild(fanSprite);
    CCRotateBy *rotate = CCRotateBy::create(0.05, 20);
    CCRepeatForever *repeat = CCRepeatForever::create(rotate);
    fanSprite->runAction(repeat);
    objectType = objectType_fan;
    
    
    for(int i =0; i < 4; i++)
    {
        wind[i] = new CCSprite();
        wind[i]->init();
        wind[i]->autorelease();
        wind[i]->setPosition(ccp(windPos[i][0],windPos[i][1] ));
        wind[i]->setOpacity(150);
        mainSprite->addChild(wind[i]);
        
        windFrameArray[i] = CCArray::create();
        windFrameArray[i]->retain();
        
        for(int j = 0; j < 5; j++)
        {
            char _tmp[8];
            sprintf(_tmp, "wind%d", (j + 1));
            CCSpriteFrame *frame = ImageManager::getFrameWithXml2(kImagesheet_GameSource, _tmp);
            windFrameArray[i]->addObject(frame);
            
            if(j == 0)
                wind[i]->setDisplayFrame(frame);
        }
    }
    cnt = 0;
    schedule(schedule_selector(FanObstacle::windtick),0.1f);

}

void FanObstacle::setBody(b2World* _world)
{
    mainSprite->setPosition(position);
    mainSprite->setRotation(bodyAngle);
}


void FanObstacle::setBodyAngle(bool isInv)
{
    if(isInv)
        bodyAngle += 10;
    else
        bodyAngle -= 10;
    mainSprite->setRotation(bodyAngle);
}

void FanObstacle::windtick(float dt)
{
    cnt = (cnt + 1) % 5;
    
    for(int i = 0; i < 4; i++)
    {
        int tmp = (cnt + countPlus[i]) % 5;
        wind[i]->setDisplayFrame((CCSpriteFrame *)windFrameArray[i]->objectAtIndex(tmp));
    }
}